package com.example.royalchef.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.royalchef.R;
import com.example.royalchef.bean.MessageEvent;
import com.example.royalchef.bean.SendPictureInfo;
import com.example.royalchef.utils.NativeImageLoader;
import com.example.royalchef.utils.PreferUtils;
import com.example.royalchef.view.AutoLayout;
import com.example.royalchef.view.CustomImageView;
import com.example.royalchef.view.FitImageView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.rockerhieu.emojicon.EmojiconEditText;
import io.github.rockerhieu.emojicon.EmojiconGridFragment;
import io.github.rockerhieu.emojicon.EmojiconsFragment;
import io.github.rockerhieu.emojicon.emoji.Emojicon;

/**
 * author: Administrator
 * created on: 2017/6/29 14:08
 * description:
 */

public class SendDynamicActivity extends AppCompatActivity implements EmojiconGridFragment.OnEmojiconClickedListener, EmojiconsFragment.OnEmojiconBackspaceClickedListener {

    private RelativeLayout pbProgress;
    private EmojiconEditText mEditEmojicon;
    private EmojiconsFragment fragment;
    private AutoLayout recyclerView;
    private ArrayList<String> checkList = new ArrayList<>();
    private ArrayList<SendPictureInfo> sendPictureInfos;
    private static final int REQUEST_CODE = 1;
    private String strImgPath = "";//照片保存路径
    private File imageFile = null;//照片文件
    private static final int PHOTORESULT = 2;
    /**
     * 定义相片的最大尺寸
     **/
    private final int IMAGE_MAX_WIDTH = 540;
    private final int IMAGE_MAX_HEIGHT = 960;
    private String content;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_dynamic);
        ButterKnife.bind(this);//绑定
        initView();
        initData();

    }

    private void initView() {
        pbProgress = (RelativeLayout) findViewById(R.id.pb_progress);
        mEditEmojicon = (EmojiconEditText) findViewById(R.id.et_send_dynamic_content);
        recyclerView = (AutoLayout) findViewById(R.id.rcv_send_dynamic);
        View inflate = View.inflate(SendDynamicActivity.this, R.layout.item_send_default, null);
        FitImageView civCamer = (FitImageView) inflate.findViewById(R.id.iv_send_dynamic_picture_default);
        civCamer.setScaleType(ImageView.ScaleType.CENTER);
        recyclerView.addView(inflate);
        inflate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeKeyboard();
                String[] items = new String[]{"从手机相册中选择", "拍照"};
                new AlertDialog.Builder(SendDynamicActivity.this)
                        .setCancelable(true)
                        .setTitle("选择图片")
                        .setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        Intent SeeIntent = new Intent(SendDynamicActivity.this, ShowImageActivity.class);
                                        startActivityForResult(SeeIntent, PHOTORESULT);
                                        dialog.dismiss();
                                        break;
                                    case 1:
                                        Intent getPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                        strImgPath = Environment.getExternalStorageDirectory()
                                                .toString() + "/Xiong_PIC/";
                                        String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
                                                .format(new Date()) + ".jpg";// 照片以格式化日期方式命名
                                        File out = new File(strImgPath);
                                        if (!out.exists()) {
                                            out.mkdirs();
                                        }
                                        out = new File(strImgPath, fileName);
                                        strImgPath = strImgPath + fileName;// 该照片的绝对路径
                                        Uri uri = Uri.fromFile(out);
                                        getPhoto.putExtra(MediaStore.EXTRA_OUTPUT, uri);//根据uri保存照片
                                        getPhoto.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);//保存照片的质量
                                        startActivityForResult(getPhoto, REQUEST_CODE);//启动相机拍照
                                        dialog.dismiss();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }).create()
                        .show();
            }
        });

    }

    private void initData() {
        sendPictureInfos = new ArrayList<>();

    }

    @OnClick({R.id.iv_send_dynamic_quit, R.id.tv_send_dynamic_send})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.iv_send_dynamic_quit:
                finish();
                break;
            case R.id.tv_send_dynamic_send:
                content = mEditEmojicon.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (checkList == null || checkList.size() == 0) {
                    Toast.makeText(SendDynamicActivity.this, "图片不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (checkList.size() < 3) {
                    Toast.makeText(SendDynamicActivity.this, "图片至少三张", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (checkList.size() > 9) {
                    Toast.makeText(SendDynamicActivity.this, "图片最多九张", Toast.LENGTH_SHORT).show();
                    return;
                }
                pbProgress.setVisibility(View.VISIBLE);
                HttpUtils http = new HttpUtils();
                RequestParams params = new RequestParams();
                for (int i = 0; i < checkList.size(); i++) {
                    params.addBodyParameter("images\"; filename=\"" + checkList.get(i), new File(checkList.get(i)));
                }
                http.send(HttpRequest.HttpMethod.POST,
                        "http://192.168.12.248:8080/upload/images.json",
                        params,
                        new RequestCallBack<String>() {

                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onLoading(long total, long current, boolean isUploading) {
                            }

                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                ArrayList<String> list = new ArrayList<>();
                                String result = responseInfo.result;
                                try {
                                    JSONObject object = new JSONObject(result);
                                    JSONArray data = object.getJSONArray("data");
                                    for (int i = 0; i < data.length(); i++) {
                                        list.add(data.get(i).toString());
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                uploadInfo(list);
                            }

                            @Override
                            public void onFailure(HttpException error, String msg) {
                                Toast.makeText(SendDynamicActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                            }
                        });

                break;
        }
    }

    private void uploadInfo(final ArrayList<String> list) {
        HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("content", content);
        String images = listToString(list, ',');
        params.addBodyParameter("images", images);
        params.addHeader("auth_token", PreferUtils.getString("authToken", ""));
        http.send(HttpRequest.HttpMethod.POST,
                "http://192.168.12.248:8080/share/insert.json",
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (total == current) {
                            pbProgress.setVisibility(View.VISIBLE);

                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        MessageEvent event = new MessageEvent();
                        event.setContent(content);
                        event.setCheckList(list);
                        EventBus.getDefault().post(event);
                        Toast.makeText(SendDynamicActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(SendDynamicActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    public void openEmojiconsActivity(View view) {
        closeKeyboard();
        fragment = EmojiconsFragment.newInstance(false);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.emojicons, fragment)
                .commit();
    }

    @Override
    public void onEmojiconClicked(Emojicon emojicon) {
        EmojiconsFragment.input(mEditEmojicon, emojicon);
    }

    @Override
    public void onEmojiconBackspaceClicked(View v) {
        EmojiconsFragment.backspace(mEditEmojicon);
    }

    @Override
    public void onBackPressed() {
        if (fragment == null) {
            new AlertDialog.Builder(SendDynamicActivity.this)
                    .setCancelable(false)
                    .setMessage("你确定放弃这条动态嘛?")
                    .setNegativeButton("继续编辑", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("放弃", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();
                        }
                    })
                    .show();
        } else {
            getSupportFragmentManager().beginTransaction().remove(fragment).commit();
            fragment = null;
        }
    }

    private void closeKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == PHOTORESULT) {
            ArrayList<String> newList = data.getStringArrayListExtra("checkList");
            for (int i = 0; i < newList.size(); i++) {
                checkList.add(newList.get(i));
                final View inflate = View.inflate(SendDynamicActivity.this, R.layout.item_send_picture, null);
                final CustomImageView civPicture = (CustomImageView) inflate.findViewById(R.id.iv_send_dynamic_picture);
                final ImageView ivDetele = (ImageView) inflate.findViewById(R.id.iv_send_dynamic_picture_delete);
                inflate.setTag(checkList.size() - 1);
                ivDetele.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Integer tag = (Integer) inflate.getTag();
                        recyclerView.removeView(inflate);
                        checkList.remove(tag);
                    }
                });
                Bitmap bitmap = NativeImageLoader.getInstance().loadNativeImage(newList.get(i), new NativeImageLoader.NativeImageCallBack() {
                    @Override
                    public void onImageLoader(Bitmap bitmap, String path) {
                        civPicture.setImageBitmap(bitmap);
                        recyclerView.addView(inflate, 0);
                    }
                });
                if (bitmap != null) {
                    civPicture.setImageBitmap(bitmap);
                    recyclerView.addView(inflate, 0);
                } else {
                    civPicture.setImageResource(R.mipmap.friends_sends_pictures_no);
                    recyclerView.addView(inflate, 0);
                }
            }
        } else if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            imageFile = new File(strImgPath);
            int scale = 0;
            scale = getZoomScale(imageFile);//得到缩放倍数
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = scale;
            final View inflate = View.inflate(SendDynamicActivity.this, R.layout.item_send_picture, null);
            inflate.setTag(checkList.size() - 1);
            final CustomImageView civPicture = (CustomImageView) inflate.findViewById(R.id.iv_send_dynamic_picture);
            final ImageView ivDetele = (ImageView) inflate.findViewById(R.id.iv_send_dynamic_picture_delete);
            ivDetele.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    recyclerView.removeView(inflate);
                    int integer = (Integer) inflate.getTag();
                    checkList.remove(integer);
                }
            });
            civPicture.setImageBitmap(BitmapFactory.decodeFile(strImgPath, options));
            recyclerView.addView(inflate, 0);
            checkList.add(imageFile.getAbsolutePath());
        } else {
            Toast.makeText(SendDynamicActivity.this, "显示失败", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 图片缩放处理
     *
     * @param imageFile 照片文件
     * @return 缩放的倍数
     */
    private int getZoomScale(File imageFile) {
        int scale = 1;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(strImgPath, options);
        while (options.outWidth / scale >= IMAGE_MAX_WIDTH
                || options.outHeight / scale >= IMAGE_MAX_HEIGHT) {
            scale *= 2;
        }
        return scale;
    }

    public String listToString(List list, char separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                sb.append(list.get(i));
            } else {
                sb.append(list.get(i));
                sb.append(separator);
            }
        }
        return sb.toString();
    }

//    public void delete(View view){
//
//    }
}
